import { Module } from 'vuex';

import type { ILoginState, IRootState } from '@/store/types';
import type { IAccount } from '@/service/login/type';
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId,
} from '@/service/login/login';

import { localCache } from '@/utils';
import { mapMenusToRoutes, mapMenusToPermission } from '@/utils/mapMenus';
import router from '@/router';

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      userInfo: {},
      token: '',
      userMenus: [],
      permissions: [],
    };
  },

  actions: {
    async accountLoginAction(ctx, payload: IAccount) {
      const { commit } = ctx;
      const loginResult = await accountLoginRequest(payload);
      const {
        data: { token, id },
      } = loginResult;

      ctx.commit('changeToken', token);
      localCache.setCache('token', token);

      // 发送初始化的请求(完整的role/department)
      ctx.dispatch('getInitialDataAction', null, { root: true });

      const userInfoResult = await requestUserInfoById(id);
      const userInfo = userInfoResult.data;
      commit('changeUserInfo', userInfo);
      localCache.setCache('userInfo', userInfo);

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id);
      const userMenus = userMenusResult.data;

      commit('changeUserMenus', userMenus);
      localCache.setCache('userMenus', userMenus);

      router.push('/main');
    },

    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token');
      const userInfo = localCache.getCache('userInfo');
      const userMenus = localCache.getCache('userMenus');

      if (token) {
        commit('changeToken', token);
      }
      if (userInfo) {
        commit('changeUserInfo', userInfo);
      }
      if (userMenus) {
        commit('changeUserMenus', userMenus);
      }
    },
  },

  mutations: {
    changeToken(state, token: string) {
      state.token = token;
    },

    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },

    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;
      const routes = mapMenusToRoutes(userMenus);

      routes.map((route) => {
        // route.meta =
        router.addRoute('main', route);
      });

      state.permissions = mapMenusToPermission(userMenus);
    },
  },
};
export default loginModule;
